/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package com.vng.zing.zprofilefrontend.model;

import com.vng.zing.calc.thrift.Profile;
import com.vng.zing.calc.thrift.ProfileSession;
import com.vng.zing.calc.thrift.SOURCE;
import com.vng.zing.logger.ZLogger;
import com.vng.zing.stats.Profiler;
import com.vng.zing.stats.ThreadProfiler;
import static com.vng.zing.zprofilefrontend.model.BaseModel.checkLogIn;
import java.io.PrintWriter;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.apache.log4j.Logger;

/**
 *
 * @author namhh
 */
public class LogOutModel extends BaseModel {

    private static final Logger _Logger = ZLogger.getLogger(LogOutModel.class);
    public static final LogOutModel Instance = new LogOutModel();

    @Override
    public void process(HttpServletRequest req, HttpServletResponse resp) {
        ThreadProfiler profiler = Profiler.getThreadProfiler();
        resp.setContentType("text/html; charset=UTF-8");
        PrintWriter out = null;
        try {
            out = resp.getWriter();
            ///TODO..
            profiler.push(this.getClass(), "output");
            ProfileSession profileSession = checkLogIn(req);
            if (null != profileSession) {
                Profile profile = getClientWithCache().getaLoad(profileSession.getId());
                if (SOURCE.FB.equals(profile.getSource())) {
                    FacebookApi.getInstance().logOut(profileSession.getAccessToken());
                } else {

                }

                getClientWithCache().removeCache(profileSession.getId());
                HttpSession session = req.getSession(false);
                if (null != session && null != session.getAttribute("profile")) {
                    session.invalidate();
                    Cookie cookie = new Cookie("JSESSIONID", null);
                    resp.addCookie(cookie);

                }
            }

            resp.sendRedirect("/login");
            profiler.pop(this.getClass(), "output");
        } catch (Exception ex) {
            _Logger.error(null, ex);
        } finally {
            if (out != null) {
                out.close();
            }
        }
    }

}
